package hong.jun.batch;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * @Description:批量执行
 * @Author: yanghongjun <1737619387@qq.com>
 * @Date: 2023/11/13
 **/
public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //创建CompletionService
        ExecutorCompletionService<Object> completionService = new ExecutorCompletionService<>(executorService);
        //存储异步任务的数组
        List<Future<Object>> futures = new ArrayList<>(3);
        futures.add(completionService.submit(Main::getprice));
        futures.add(completionService.submit(Main::getprice));
        futures.add(completionService.submit(Main::getprice));
        Integer result;

        try {
            for (int i = 0; true; i++) {
                //System.out.println("i=" + i);
                //获取结果会阻塞。通过后再进行下一个循环，第一个打印的就是最先执行完的异步结果
                result = (Integer) completionService.take().get();
                break;
            }
        } finally {
            //获取完第一个结果后，取消所有异步任务
            for (Future<Object> future : futures) {
                future.cancel(true);
            }
        }
        System.out.println("获取的第一个结果为" + result);
    }

    public static Integer getprice() throws InterruptedException {
        Random random = new Random();
        Thread.sleep(random.nextInt(2000, 10000));
        //Thread.sleep(5000);
        return random.nextInt(10);
    }
}
